/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package czat;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JOptionPane;

/**

@author zztbak01
 */
public class WatekKlienta extends Thread {

	Socket socket;
	OutputStream os;
	Scanner sc;
	ChatClient klient;

	public WatekKlienta() throws IOException {
		socket = new Socket("localhost", StaticPorts.ServerPort);
		os = socket.getOutputStream();
		sc = new Scanner(socket.getInputStream());
	}

	public void wyslij(String text) {
		try {
			os.write((text + "\n").getBytes());
		} catch (IOException ex) {
		}
	}

	public String czytaj() {
		return sc.nextLine();
	}

	@Override
	public void run() {
		String line;
		while (true) {
			try {
				line = czytaj();
			} catch (Exception e) {
				int ans = JOptionPane.showConfirmDialog(null,
								"Połączenie z serwerem zostało utracone.\n"
								+ " Czy chcesz zamknąć aplikację?", "Błąd serwera!", JOptionPane.ERROR_MESSAGE);
				if (ans <= 0) {
					klient.dispose();
				}
				return;
			}
			System.out.println(line);
			String[] napisy = line.split(";", 2);
			if (napisy[0].equals("ADD")) {
				klient.addActiveUser(napisy[1]);
			}
			if (napisy[0].equals("REMOVE")) {
				klient.removeActiveUser(napisy[1]);
			}
			if (napisy[0].equals("TEXT")) {
				napisy = napisy[1].split(";", 2);
				klient.addText(napisy[0], klient.login, napisy[1]);
			}
		}
	}
}
